//
//  WXOAuthViewController.swift
//  weibo
//
//  Created by 王旭 on 16/4/19.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit
import SVProgressHUD

//AppKey
let WB_APP_KEY = "1498489312"
//回调页
let WB_REDIRECT_URI = "http://www.baidu.com/"
// APP_SECRET
let WB_APP_SECRET = "824ce8e7a8ab9529b24c6cbcd7ab21bf"

class WXOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加NaviagetionBarButton
        setupUI()
        
        //webView加载请求界面
        let ReqUrlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        let url = NSURL(string: ReqUrlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)

    }
    
//添加NaviagetionBarButton
    func setupUI() {
        //背景色
        view.backgroundColor = UIColor.whiteColor()
        //中间文字
        title = "登录"
        //左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        //右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
//关闭按钮调用方法
  @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
//自定填充按钮调用方法
    @objc private func autoFill() {
        let jsStr = "document.getElementById('userId').value='13248398260';document.getElementById('passwd').value='897571xlwb'"
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
//webView懒加载
    private lazy var webView : UIWebView = { ()->UIWebView in
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
}

//用来实现UIWebViewDelegate 的代理方法的
extension WXOAuthViewController: UIWebViewDelegate{
    
//webView将要加载一个request的时候调用
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request)
        
        //获取请求的url
        guard let url = request.URL else {
            return false
        }
        
//        print(request.URL)
        
        //判断url是否以回调页开头
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI) {
            
//            print(url.query)
            
            //判断url是否包含某个字符串--containsString
            guard let q = url.query where q.containsString("code=") else {
                return false
            }
            
            //截取授权code
            let code = q.substringFromIndex("code=".endIndex)
            
//            print(code)
            
            //通过code获取access Token --032a434d7db8714dd58bc1cc8414542c
//            getAccessToken(code)
            WXUserAccountViewModel.sharedUserAccountViewModel.getAccessToken(code,finished:{(isSuccess)->()in
                if isSuccess {
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        
//                        let applicationDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//                        applicationDelegate?.window?.rootViewController = WXWelcomeViewController()
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(WXChangeRootVCNotification, object: nil)
                        
                    })
                    print("登录成功，关闭当前界面切换控制器")
                }else{
                    print("登录失败")
                }
            })
            
        }
        return true
    }
    

    
    
//webView加载完成前的效果
//webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
//webView结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
}